package com.example.testsbjenkins.DynamicProxyAndReflex;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author: lt
 * @date: 2022/7/6 18:24
 * @Description: todo
 */
public class TestReflex {
    
    
    class Person {

        private int age;
        private String name;
        public Person() {
        }
        private Person(String name){
            this.name = name;
        }
        public Person(int age,String name){
            this.age = age;
            this.name = name;
        }
        //省略set/get方法
        @Override
        public String toString() {
            return "Person{" +
                    "age=" + age +
                    ", name='" + name + '\'' +
                    '}';
        }
        
    }


    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {

        //外部类
        Class<?> out = Class.forName("com.example.testsbjenkins.DynamicProxyAndReflex.TestReflex");
        //此处调用的是内部类 所以需要与外部类 通过 $ 拼接
        Class<?> PersonClass = Class.forName("com.example.testsbjenkins.DynamicProxyAndReflex.TestReflex$Person");

       /* //获取所有的属性
        Field[] declaredFields = PersonClass.getDeclaredFields();
        System.out.println("class的所有属性");
        Arrays.stream(declaredFields).forEach(System.out::println);
        System.out.println("class的所有public属性");
        Field[] fields = PersonClass.getFields();
        Arrays.stream(fields).forEach(System.out::println);
        */
        {
            //获取class某个属性的值
            Constructor<?> declaredConstructor = PersonClass.getDeclaredConstructors()[0];
            declaredConstructor.setAccessible(true);
            Object zs = declaredConstructor.newInstance(out.newInstance(),1,"zs");
            Field field = PersonClass.getDeclaredField("name");
            field.setAccessible(true);
            System.out.println("name 属性的值是:"+ field.get(zs));

        }
        
        //Constructor<?> declaredConstructor = PersonClass.getDeclaredConstructors()[0];
        //declaredConstructor.setAccessible(true);
        //
        ////经测试 参数列表不同的构造方法 默认会找参数多的那个
        //Object o = declaredConstructor.newInstance(out.newInstance(),1,"a");
        //
        //System.out.println("Person类的带一个int,一个String 参数的构造函数,返回的对象信息是:" + o.toString());

    }
    
}
